package com.situ.personal.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.personal.entity.User;

@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath : " + servletPath);
		
		int lastIndex = servletPath.lastIndexOf(".");
		String extension = "";
		if (lastIndex != -1) {
			extension = servletPath.substring(lastIndex); // .js   .css  .png
		}
		
		// 对特殊的请求不需要登录验证
		if ("/user_login.jsp".equals(servletPath) 
				|| "/loginServlet".equals(servletPath)
				|| "/checkCode".equals(servletPath)
				|| ".js".equals(extension)
				|| ".css".equals(extension)
				|| ".png".equals(extension)) {
			chain.doFilter(request, response);
		} else {// 需要验证
			HttpSession session = httpServletRequest.getSession();
			User user = (User)session.getAttribute("user");
			// user是null，没有登录情况下，需要重定向到登录界面，但是访问user_login.jsp
			// 也会被拦截，也需要登录。问题就是：要去登录界面但是到登录界面要求你必须是登录状态。
			// 解决方法就是：给一些特殊的请求不进行登录验证，例如：user_login.jsp、/loginServlet
			if (user == null) {
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/user_login.jsp");
				return;
			}
			  
			chain.doFilter(request, response);
		}
		
		
		
		
	}

	@Override
	public void destroy() {
	}

}
